package com.mytecblog.framework.advice;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.util.List;

/**
 * 统一处理验证失败异常
 * 如果是普通提交则验证失败后跳转到validError.jsp，如果是ajax提交则向response中写入失败信息
 * 使用此切片后@Valid注解验证的参数后不用再加Errors或BindResult
 * @author yg.huang
 * @version v1.0
 *          DATE  2016/11/25
 */
@ControllerAdvice
@Controller
public class ValidateControllerAdvice {
    Logger logger=Logger.getLogger(ValidateControllerAdvice.class);
    /**
     * bean校验未通过异常
     *
     * @see javax.validation.Valid
     * @see org.springframework.validation.Validator
     * @see org.springframework.validation.DataBinder
     */
    @ExceptionHandler(BindException.class)
    public String illegalParamsExceptionHandler(BindException e,WebRequest request) {


        List<FieldError> fieldErrors=e.getBindingResult().getFieldErrors();
        for (FieldError error:fieldErrors){
            logger.error(error.getField()+":"+error.getDefaultMessage());
        }

        request.setAttribute("fieldErrors",fieldErrors,WebRequest.SCOPE_REQUEST);
        return "/validError";
    }

}
